package bo.zhao.action.interpreter;

import java.util.Stack;

/**
 * @author Bo.Zhao
 * @since 19/6/12
 */
public class Client {
    public static void main(String[] args) {
        String tokenString = "4 3 2 - 1 + *";
        Stack<Expression> stack = new Stack<>();
        String[] split = tokenString.split(" ");
        for (String s : split) {
            if (isOperator(s)) {
                Expression rightExpression = stack.pop();
                Expression leftExpression = stack.pop();

                System.out.println(String.format("popped from stack left: %s right: %s", leftExpression.interpret(), rightExpression.interpret()));
                Expression operator = getOperatorInstance(s, leftExpression, rightExpression);
                System.out.println("operator " + operator);

                int result = operator.interpret();
                NumberExpression resultExpression = new NumberExpression(result);
                stack.push(resultExpression);
                System.out.println(String.format("push result to stack: %s", resultExpression.interpret()));
            } else {
                Expression i = new NumberExpression(s);
                stack.push(i);
                System.out.println(String.format("push to stack: %s", i.interpret()));
            }
        }
    }


    public static boolean isOperator(String s) {
        return s.equals("+") || s.equals("-") || s.equals("*");
    }

    public static Expression getOperatorInstance(String s, Expression left, Expression right) {
        switch (s) {
            case "+":
                return new PlusExpression(left, right);
            case "-":
                return new MinusExpression(left, right);
            case "*":
                return new MultiplyExpression(left, right);
            default:
                return new MultiplyExpression(left, right);
        }
    }
}
